package com.mengshu.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mengshu.mybatisplus.basic.BasicPO;
import com.mengshu.mybatisplus.utils.RequestUtils;
import com.mengshu.token.api.LoginService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.reflection.MetaObject;

@RequiredArgsConstructor
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_ID = "createId";

    private static final String UPDATE_ID = "updateId";

    private static final String CLIENT_IP = "clientIp";

    private final LoginService loginService;

    @Override
    public void insertFill(MetaObject metaObject) {
        if (ignoreClass(metaObject.getOriginalObject())) { return; }
        Object fieldValue = getFieldValByName(CREATE_ID, metaObject);
        if (fieldValue == null) {
            setFieldValByName(CREATE_ID, getUserId(), metaObject);
        }
        fieldValue = getFieldValByName(UPDATE_ID, metaObject);
        if (fieldValue == null) {
            setFieldValByName(UPDATE_ID, getUserId(), metaObject);
        }
        fieldValue = getFieldValByName(CLIENT_IP, metaObject);
        if (fieldValue == null) {
            setFieldValByName(CLIENT_IP, getClientIp(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ignoreClass(metaObject.getOriginalObject())) { return; }
        setFieldValByName(UPDATE_ID, getUserId(), metaObject);
        setFieldValByName(CLIENT_IP, getClientIp(), metaObject);
    }

    private boolean ignoreClass(Object object) {
        return !BasicPO.class.isAssignableFrom(object.getClass());
    }

    private Long getUserId() {
        return loginService == null ? null : loginService.getLoginUserId();
    }

    private String getClientIp() {
        return RequestUtils.getIp();
    }

}
